package com.ruoyi.user.interceptor;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.user.enums.BizCodeEnum;
import com.ruoyi.user.model.LoginUser;
import com.ruoyi.user.utils.CommonUtil;
import com.ruoyi.user.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * @author Lu.F
 * @version 1.0
 * @date 2022/11/10 16:22
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 标记登录
     */
    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        try {
            String accessToken = request.getHeader("token");
            if (StringUtils.isBlank(accessToken)) {
                accessToken = request.getHeader("access-header");
            } else if (StringUtils.isBlank(accessToken)) {
                accessToken = request.getParameter("token");
            }

            if (StringUtils.isNotBlank(accessToken)) {
                Claims claims = JwtUtil.parseToken(accessToken);
                if (claims == null) {
                    CommonUtil.sendJsonMessage(response, AjaxResult.error(BizCodeEnum.ACCOUNT_UNLOGIN_ERROR.getMsg()));
                    return false;
                }
                String uname = claims.get("uname", String.class);
                String utell = claims.get("utell", String.class);
                Long id = claims.get("id", Long.class);
                LoginUser loginUser = new LoginUser();
                loginUser.setId(id);
                loginUser.setUname(uname);
                loginUser.setUtell(utell);
                threadLocal.set(loginUser);
                return true;
            }
        } catch (Exception e) {
            log.warn("拦截器异常 ", e);
            return false;
        }
        CommonUtil.sendJsonMessage(response, AjaxResult.error(BizCodeEnum.ACCOUNT_UNLOGIN_ERROR.getMsg()));
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
